<?php

namespace app\api\controller;

use app\api\service\LoginService;
use app\api\service\RechargeService;
use app\BaseController;
use app\common\service\CommonWechatPayService;
use think\facade\Request;
use think\facade\Log;
use app\Response;
class Recharge extends BaseController
{

    /*微信充值余额*/
    public function wxRechargBalance(){
        if (Request::isPost()) {
            $user_id = LoginService::getUserIdFromToken();
            if(!is_numeric($user_id)){
                return $user_id;
            }
            $data = $this->request->post();
            try{
                $this->validate($data, 'RechargBalance');
            }catch (\Exception $e){
                return json(['code' => 0, 'msg' => lang($e->getMessage()), 'data' => [], 'count' => '']);
            }
            $payInfo = RechargeService::wxRechargBalanceService($user_id,$data);
            return $payInfo;
        }
    }


    /*微信支付回调*/
    public function wxRechargRoBack(){
        $data = CommonWechatPayService::xmlStructureToArray(file_get_contents('php://input'));
        Log::info('微信支付回调记录！ ' . json_encode($data));
        if ($data['return_code'] == 'SUCCESS' && $data['result_code'] == 'SUCCESS') {
            if(isset($data["attach"])&&!empty($data["attach"])){
               $attach = (array)json_decode($data["attach"]);
                if(isset($attach["type"])&&$attach["type"] == 1){
                    CommonWechatPayService::wxOrderPayRollBack($data);//单商品下单支付成功回调处理
                }elseif(isset($attach["type"])&&$attach["type"]==2){
                    CommonWechatPayService::wxCartOrderPayRollBack($data);//购物车下单支付成功回调处理
                }
               echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
               Log::info('微信支付成功1！ ' . json_encode($data));
            }else{
                echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                Log::info('微信支付成功2！ ' . json_encode($data));
            }
        }else{
            Log::info('微信支付失败！ ' . json_encode($data));
        }
        return Response::wrapData();
    }

}